#Author: 0x9DEFA478

Exist_BUILD_PREFIX=0
BUILD_PREFIX=""
InputExec=""

options=$(getopt -o p:e: --long BUILD_PREFIX:,InputExec: -n $0 -- "$@")
if (( $? != 0 )); then
  exit 1
fi
eval set -- "${options}"
while true
do
  case $1 in
    -p|--BUILD_PREFIX)
      BUILD_PREFIX=$2
      Exist_BUILD_PREFIX=1
      shift 2
    ;;
    -e|--InputExec)
      InputExec=$2
      shift 2
    ;;
    --)
      shift
      break
    ;;
    *)
      echo "$0 param decode error $1"
      exit 1
    ;;
  esac
done

if [[ $InputExec == "" ]]; then
  echo -e "\e[31mno option InputExec\e[0m"
  exit 1
fi

if (( $# < 1 )); then
  echo -e "\e[31mno LibRelDirList\e[0m"
  exit 1
fi

FullName=$(which "${BUILD_PREFIX}gcc")

InputExec=${InputExec//'\'/'/'}
ExecFullPath=$(dirname $InputExec)

"${BUILD_PREFIX}objdump" -x $InputExec | grep "DLL Name:" | while read -r item; do

  item=${item##*DLL Name:}
  item=$(echo $item)

  Res=0
  ResDir=""
  for LibRelDir in "$@"; do
    LibPath=$(dirname $FullName)$LibRelDir
    if [[ -e "${LibPath}/${item}" ]]; then
      cp -f "${LibPath}/${item}" "${ExecFullPath}/${item}"
      Res=1
      ResDir=$LibRelDir
      break
    fi
  done
  if (( Res != 0 )); then
    echo -e "\e[34m${item} \e[32mOK\e[0m in ${ResDir}"
  else
    echo -e "\e[34m${item} \e[31mFAIL\e[0m"
  fi
done

